package com.base.system.config;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import cn.hutool.captcha.generator.RandomGenerator;
import cn.hutool.core.util.StrUtil;
import com.base.system.enums.HttpStatus;
import com.base.system.exception.HttpException;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.Random;

/**
 * 验证码
 */
@Slf4j
public class RandomValidateCode {
    public static final String RANDOMCODEKEY = "RANDOMVALIDATECODEKEY";//放到session中的key
    //private String randString = "0123456789";//随机产生只有数字的字符串 private String
    //private String randString = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";//随机产生只有字母的字符串
    private static String randString = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";//随机产生数字与字母组合的字符串

    private static int width = 200;// 图片宽
    private static int height = 50;// 图片高
    private static int stringNum = 5;// 随机产生字符数量

    private Random random = new Random();

    /**
     * 生成随机图片
     *
     * @param request
     * @param response
     */
    public void getRandcode(HttpServletRequest request, HttpServletResponse response) {
        HttpSession session = request.getSession();
        RandomGenerator randomGenerator = new RandomGenerator(randString, stringNum);
        LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(width, height);
        lineCaptcha.setGenerator(randomGenerator);
        log.info("验证码:{}", lineCaptcha.getCode());
        //将生成的随机字符串保存到session中
        session.removeAttribute(RANDOMCODEKEY);
        session.setAttribute(RANDOMCODEKEY, lineCaptcha.getCode());
        try {
            // 将内存中的图片通过流动形式输出到客户端
            lineCaptcha.write(response.getOutputStream());
        } catch (Exception e) {
            log.error("将内存中的图片通过流动形式输出到客户端失败>>>>   ", e);
        }

    }

    public void checkRandCode(HttpSession session, String inputCode) {
        String attribute = (String) session.getAttribute(RANDOMCODEKEY);
        if (StrUtil.isEmpty(attribute) || !StrUtil.equalsAnyIgnoreCase(attribute, inputCode))
            throw new HttpException(HttpStatus.yzm_error);
        session.removeAttribute(RANDOMCODEKEY);
    }
}
